package com.atguigu.spzx.model.vo.common;

import lombok.Data;
import lombok.experimental.Accessors;

import java.util.HashMap;
import java.util.Map;
@Data
//@Accessors(chain = true)//启用链式调用
public class R {
    private Integer code;
    private String message;
    private Map<String,Object> data = new HashMap<>();
/*
    R对象的json
        {
            code: 1,
            message: 'xx',
            data: {
                k:v,
                k:v
            }
        }
      R.ok() ==> {code:1,message:xx}
      R.ok("token","rqwrqwrqrq") ==> {code:1,message:xx,data:{token:"rqwrqwrqrq"}}
      R.ok("token","rqwrqwrqrq").data("refresh_token","sfasfassf") ==> {code:1,message:xx,data:{token:"rqwrqwrqrq","refresh_token":"xxxx"}}
        Map map = new HashMap();
            map.put("token","xxx");

            R.ok().data(map);

 */

    //提供静态工具方法初始化R对象
    //默认成功
    public static R ok(String key , Object data){
        R r = R.setResult(ResultCodeEnum.SUCCESS);
        r.data.put(key,data);
        return r;
    }
    public static R ok(){
        R r = R.setResult(ResultCodeEnum.SUCCESS);
       // r.data.put(key,data);
        return r;
    }
    //默认失败
    //硬编码：
    public static R fail(){
        return R.setResult(ResultCodeEnum.ERROR);
    }
    //自定义失败
    public static R setResult(Integer code,String message){
        R r = new R();
//        r.code = code;
//        r.message = message;
        r.setCode(code);
        r.setMessage(message);
        return r;
    }
    public static R setResult(ResultCodeEnum codeEnum){
        R r = new R();
//        r.code = code;
//        r.message = message;
        r.setCode(codeEnum.getCode());
        r.setMessage(codeEnum.getMesssage());
        return r;
    }
    //提供自定义的链式调用方法修改其他的属性值
    public R data(Map<String,Object> map){
        this.data = map;
        return this;
    }
    public R data(String key  , Object val){
        this.data.put(key,val);
        return this;
    }
    public R code(Integer code){
        this.code = code;
        return this;
    }
    public R message(String message){
        this.message = message;
        return this;
    }
}
